package bsi.vn.FirstApp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import bsi.vn.Lib.DBAdapter;
import bsi.vn.Lib.Consts;
import bsi.vn.Lib.ProcessFunc;

import android.app.AlertDialog;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity{
	// Values for email and password at the time of the login attempt.
	private String mAccount;
	private String mPassword;
	private Intent intent;
	
	private DBAdapter dbAdapter;
	
	// UI references.
	private EditText mAccountView;
	private EditText mPasswordView;
	private CheckBox cbRememberMe;
	private View mLoginFormView;
	private View mLoginStatusView;
	
	private String aCookieInfo[];

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);
		
		mPasswordView = (EditText) findViewById(R.id.password);
		mAccountView = (EditText)findViewById(R.id.account);
		cbRememberMe = (CheckBox)findViewById(R.id.lgcbRememberMe);
		
		
		File file = new File(Consts.F_COOKIE);
		if(file.exists()) 
		{
			aCookieInfo = ProcessFunc.ReadFromFile(this, Consts.F_COOKIE).split("\\|");
			cbRememberMe.setChecked(true);
			mAccountView.setText(aCookieInfo[0].trim());
			mPasswordView.setText(aCookieInfo[1].trim());
		}
	
		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		
		
		mPasswordView
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							CheckDataValid();
							return true;
						}
						return false;
					}
				});
		
		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
				   		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
					    {
				   			if (CheckDataValid())
				   			{
				   				File file = new File(Consts.F_COOKIE);
								if (cbRememberMe.isChecked())
								{
									if(!file.exists())
										try {
											ProcessFunc.WriteToFile(LoginActivity.this, Consts.F_COOKIE, mAccountView.getText().toString() + "|" + mPasswordView.getText().toString());
										} catch (FileNotFoundException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
								}
				   				else
				   					file.delete();
				   				
				   				myAsyncTask myWebFetch = new myAsyncTask();
				   				myWebFetch.execute();
				   			}
					    }
					    else
					    	showGPSDisabledAlertToUser();
					}
				});
	}
	
	
	private class myAsyncTask extends AsyncTask<String, String, String>    {
        
		@Override 	
		protected String doInBackground(String... params) {
			InputStream is = null;
			
			try {
				
				mAccountView = (EditText) findViewById(R.id.account);
				mAccount = mAccountView.getText().toString();
				
				mPasswordView = (EditText) findViewById(R.id.password);
				mPassword = mPasswordView.getText().toString();

				HttpClient httpClient = new DefaultHttpClient();
	            HttpPost httpPost = new HttpPost(Consts.MAIN_URL);
            
	            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
	            nameValuePair.add(new BasicNameValuePair("func", "1"));
	            //nameValuePair.add(new BasicNameValuePair("uname",mAccount));
	            //nameValuePair.add(new BasicNameValuePair("pass",ProcessFunc.getMd5Hash(mPassword)));
	            //nameValuePair.add(new BasicNameValuePair("pass",mPassword));
	            nameValuePair.add(new BasicNameValuePair("uname","duongv"));
	            nameValuePair.add(new BasicNameValuePair("pass","96e79218965eb72c92a549dd5a330112"));
	           
	            
	            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
	            HttpResponse response = httpClient.execute(httpPost);
	            HttpEntity entity = response.getEntity();
	    		is = entity.getContent();
	            try{
		    		BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		    		StringBuilder sb = new StringBuilder();
		    		String line = null;
		    		while ((line = reader.readLine()) != null) {
		    			sb.append(line + "\n");
		    		}
		    		is.close();
		    		return sb.toString();
		        }
				catch(Exception e){
		    		Log.e("test", "Error converting result "+e.toString());
		    	}
	     	} 
			catch (ClientProtocolException  e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "";
		}
		
		@Override
		protected void onPostExecute(String result) {
			String sResponse[] = result.split("\\|");
			for (int i = 0; i< sResponse.length;i++){
				Log.d("test", sResponse[i]);
			}
			if (sResponse.length <= 0)
			{
				ProcessFunc.ShowSimpleDialog(LoginActivity.this, getString(R.string.liDialogBoxHeader), getString(R.string.liLoginError));
				return;
			}
    		int iResponseCode = Integer.parseInt(sResponse[0]);
    		
    		if (iResponseCode == -1)
    		{
    			ProcessFunc.ShowSimpleDialog(LoginActivity.this, getString(R.string.liDialogBoxHeader), sResponse[1].trim());
				return;
    	      }
    		else
    		{
    			int iUserId = Integer.parseInt(sResponse[1]);
    			int iUserType = Integer.parseInt(sResponse[3]);
    			String sCookie = sResponse[4];
    			String sIpAddress = sResponse[5];
    		
    			dbAdapter = new DBAdapter(LoginActivity.this);
    			dbAdapter.open();
    			dbAdapter.deleteTable(Consts.TABLE_COOKIE);
        		long insertFlag = 0;
        		insertFlag = dbAdapter.insertCookieTbl(iUserId,iUserType,sCookie,sIpAddress);
        		if (insertFlag <= 0){
        			ProcessFunc.ShowSimpleDialog(LoginActivity.this, getString(R.string.liDialogBoxHeader), getString(R.string.liUpdateCookie));
    				return;
        		}
        		else
        		{
        			//intent = new Intent(LoginActivity.this, MainActivity.class);
        			intent = new Intent(LoginActivity.this, TicketFragmentActivity.class);
        			startActivity(intent);
        		}
        		dbAdapter.close();
        	}
    		
    		
		}
		
        @Override
        protected void onPreExecute() {
        	super.onPreExecute();
     		showProgress(true);
        }
        
        @Override
        protected void onProgressUpdate(String... text) {
         //finalResult.setText(text[0]);
         // Things to be done while execution of long running operation is in
         // progress. For example updating ProgessDialog
        }
 	}

	private void showGPSDisabledAlertToUser(){
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder.setMessage(R.string.liGPSMessage)
			.setCancelable(false)
			.setPositiveButton(R.string.liGPSHeader,
					new DialogInterface.OnClickListener(){
						@Override
						public void onClick(DialogInterface dialog, int id){
							Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							startActivity(callGPSSettingIntent);
						}
		});
		alertDialogBuilder.setNegativeButton(R.string.liGPSButton,
			new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int id){
					//dialog.cancel();
					System.exit(0);
				} 
		});
		AlertDialog alert = alertDialogBuilder.create();
		alert.show();
	}


	public boolean CheckDataValid() {
		
		// Store values at the time of the login attempt.
		mAccountView = (EditText) findViewById(R.id.account);
		mAccount = mAccountView.getText().toString();
		
		mPassword = mPasswordView.getText().toString();
		mPasswordView = (EditText) findViewById(R.id.password);
		
		if (TextUtils.isEmpty(mAccount)) {
			mAccountView.setError(getString(R.string.error_field_required));
			mAccountView.requestFocus();
			return false;
		}
		
		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			mPasswordView.requestFocus();
			return false;
		} 
		else if (mPassword.length() < 6) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			mPasswordView.requestFocus();
			return false;
		}
		return true;
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}
}
